#!/bin/bash
#modify config file
#2020/1/3
#kevin

conf_file=$1
standard_file=$2
#echo $conf_file $standard_file
diff_file="./different.txt"

conf_temp_file="./a.temp"
standard_temp_file="./b.temp"

arr_conf_value=
arr_conf_key=
arr_standard_value=
arr_standard_key=


#delete file
delFile(){
	if [ -e $1 ];then
	rm -fr $1
	fi
}

#$1--old_file $2--new_file. delete # line ,space line and ; line  
delspecsymbol(){
	
	cat $1 | grep -v '^#\|^;\|^$\|^ ' |sed -r 's/ //g;s/\t//g' | sort -n | uniq > $2

}

getStandardArr(){
	i=0
	#get standard file key and value
	for line in `cat $standard_temp_file`
		do	
        
		arr_standard_value[$i]=`echo $line | cut -d '=' -f2`
	
		#get the key of config file 
		arr_standard_key[$i]=`echo $line | cut -d '=' -f1`

       		#echo ${arr_standard_key[$i]}
		#echo "${arr_standard_value[$i]}"
	
		i=$(( $i + 1 ))
	done
}

#get the different value form standard file
getDiffValue(){
	count=${#arr_standard_value[*]}
	for((i=0;i<$count;i++));
	do
		key=${arr_standard_key[$i]}
		value=${arr_standard_value[$i]}

		str_conf=`cat $conf_temp_file | grep "$key="`
		str_standard="$key=$value"
		if [ "$str_conf" = "" ];then
			echo $str_standard >> $conf_file
			echo $str_standard >> $diff_file
		else
			if [ "$str_conf" != "$str_standard" ];then
			
				modifyValue $str_conf $str_standard $conf_file
				echo $str_conf >> $diff_file
			fi
		fi
	done
}


#useage: modifyValue $str_conf $str_standard $conf_file
modifyValue(){
		sed -i s/$1/$2/g $3
}

#exit if parameters are wrong
if [ $# -lt 2 ];then
	echo "useage: ./modify.sh conf_file standard_file"
	exit
fi

#delete diff_file if exsit the file
delFile $diff_file

delspecsymbol $standard_file $standard_temp_file
delspecsymbol $conf_file $conf_temp_file
getStandardArr
getDiffValue

#delete temp file
delFile $conf_temp_file
delFile $standard_temp_file
